

<!DOCTYPE html>
<html lang="en" color-mode=light>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Java 面向对象入门 - Alex</title>
  <meta name="apple-mobile-web-app-capable" content="yes" />
  <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
  <meta name="google" content="notranslate" />
  
  <meta name="description" content="目标读者:
了解 Java 基本数据类型，权限修饰符，...">
  <meta name="author" content="Alex">
  <link rel="icon" href="/images/icons/favicon-16x16.png" type="image/png" sizes="16x16">
  <link rel="icon" href="/images/icons/favicon-32x32.png" type="image/png" sizes="32x32">
  <link rel="apple-touch-icon" href="/images/icons/apple-touch-icon.png" sizes="180x180">
  <meta rel="mask-icon" href="/images/icons/stun-logo.svg" color="#333333">
  
    <meta rel="msapplication-TileImage" content="/images/icons/favicon-144x144.png">
    <meta rel="msapplication-TileColor" content="#000000">
  

  
<link rel="stylesheet" href="/css/style.css">


  
    
<link rel="stylesheet" href="//at.alicdn.com/t/font_1445822_s6x2xcokxrl.css">

  

  
    
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.css">

  

  
    
      
        
        
<link rel="stylesheet" href="https://cdn.bootcss.com/highlight.js/9.18.1/styles/xcode.min.css" name="highlight-style" mode="light">

      
        
        
<link rel="stylesheet" href="https://cdn.bootcss.com/highlight.js/9.18.1/styles/solarized-dark.min.css" name="highlight-style" mode="dark">

      
  

  <script>
    var CONFIG = window.CONFIG || {};
    var ZHAOO = window.ZHAOO || {};
    CONFIG = {
      isHome: false,
      fancybox: true,
      pjax: false,
      lazyload: {
        enable: true,
        only_post: 'false',
        loading: '/images/theme/loading.gif'
      },
      donate: {
        enable: true,
        alipay: 'https://pic.izhaoo.com/alipay.jpg',
        wechat: 'https://pic.izhaoo.com/wechat.jpg'
      },
      galleries: {
        enable: true
      },
      fab: {
        enable: true,
        always_show: false
      },
      carrier: {
        enable: true
      },
      daovoice: {
        enable: false
      },
      preview: {
        background: {
          default: '/images/theme/welcome-image.jpg',
          api: ''
        },
        motto: {
          default: '我在开了灯的床头下，想问问自己的心啊。',
          api: 'https://v2.jinrishici.com/one.json',
          data_contents: '["data","content"]'
        },
      },
      qrcode: {
        enable: true,
        type: 'url',
        image: 'https://pic.izhaoo.com/weapp-code.jpg',
      },
      toc: {
        enable: true
      },
      scrollbar: {
        model: 'simple'
      },
      notification: {
        enable: false,
        delay: 4500,
        list: '',
        page_white_list: '',
        page_black_list: ''
      }
    }
  </script>

  

  

<meta name="generator" content="Hexo 5.1.1"></head>

<body class="lock-screen">
  <div class="loading"></div>
  


  <nav class="navbar">
    <div class="left">
      
        <i class="iconfont iconqrcode j-navbar-qrcode"></i>
      
      
        <i class="iconfont iconmoono" id="color-toggle" color-toggle="light"></i>
      
    </div>
    <div class="center">Java 面向对象入门</div>
    <div class="right">
      <i class="iconfont iconmenu j-navbar-menu"></i>
    </div>
    
      <div id="qrcode-navbar"></div>
    
  </nav>

  

<nav class="menu">
  <div class="menu-wrap">
    <div class="menu-close">
      <i class="iconfont iconbaseline-close-px"></i>
    </div>
    <ul class="menu-content"><li class="menu-item">
        <a href="/ " class="underline "> 首页</a>
      </li><li class="menu-item">
        <a href="/galleries/ " class="underline "> 摄影</a>
      </li><li class="menu-item">
        <a href="/archives/ " class="underline "> 归档</a>
      </li><li class="menu-item">
        <a href="/tags/ " class="underline "> 标签</a>
      </li><li class="menu-item">
        <a href="/categories/ " class="underline "> 分类</a>
      </li><li class="menu-item">
        <a href="/about/ " class="underline "> 关于</a>
      </li></ul>
    
      <div class="menu-copyright"><p>Powered by <a target="_blank" href="https://hexo.io">Hexo</a>  |  Theme - <a target="_blank" href="https://github.com/izhaoo/hexo-theme-zhaoo">zhaoo</a></p></div>
    
  </div>
</nav>
  <main id="main">
  <div class="article-wrap">
    <div class="row container">
      <div class="col-xl-3"></div>
      <div class="col-xl-6"><article class="article">
  <div class="wrap">
    <section class="head">
  <img   class="lazyload" data-original="/images/theme/post-image.jpg" src=""  draggable="false">
  <div class="head-mask">
    <h1 class="head-title">Java 面向对象入门</h1>
    <div class="head-info">
      <span class="post-info-item"><i class="iconfont iconcalendar"></i>November 07, 2020</span>
      
      <span class="post-info-item"><i class="iconfont iconfont-size"></i>27930</span>
    </div>
  </div>
</section>
    <section class="main">
      <section class="content">
        <h2 id="抽象类"><a href="#抽象类" class="headerlink" title="抽象类"></a>抽象类</h2><ul>
<li><p>关键字 <code>abstract</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// 用abstract关键字修饰的类就是抽象类。</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">People</span> </span>&#123;<br>    <span class="hljs-comment">//...</span><br>&#125;<br></code></pre></td></tr></table></figure>
</li>
<li><p>抽象类和普通类的区别：</p>
<ol>
<li><p>抽象类不能被实例化</p>
</li>
<li><p>抽象类的子类必须实现它的抽象方法，除非这个子类也是抽象类。</p>
</li>
<li><p>抽象类可以拥有抽象方法。普通的类不能拥有抽象方法。</p>
<blockquote>
<p>抽象方法：</p>
<p>被<code>abstract</code>关键字修饰的方法就是抽象方法。</p>
<p>抽象方法需要被子类实现，即重写（Override）。如果子类也是抽象类，那么可以不重写抽象方法，或者重写其中几个。</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">People</span> </span>&#123;<br>    <span class="hljs-comment">// 将会说出的一段话。e.g 我是杨晨</span><br>    <span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">abstract</span> String <span class="hljs-title">words</span><span class="hljs-params">()</span></span>;<br>    <span class="hljs-comment">// 做出一个动作。e.g 露出开心的笑容</span><br>    <span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">abstract</span> String <span class="hljs-title">action</span><span class="hljs-params">()</span></span>;<br>&#125;<br></code></pre></td></tr></table></figure>

</li>
</ol>
</li>
</ul>
<p>这是一个例子：</p>
<ul>
<li>需求：</li>
</ul>
<p>​    我们需要定义<strong>老师和学生</strong>。他们都是<strong>人</strong>，都拥有<strong>年龄</strong>和名字。每个人<strong>都可以做一件事</strong>：先做一个动作，然后再说一句话。每个人的<strong>动作可以不同</strong>，说的<strong>话也可以不同</strong>。</p>
<p>​    <strong>老师</strong>需要教一门课程，在老师说话时需要说出自己教的课程名称。</p>
<p>​    对<strong>学生</strong>没有特殊要求。</p>
<ul>
<li><p>定义抽象类<code>People</code></p>
<p>​    根据需求，可以将老师和同学共同的部分抽象出来，组成抽象类。这样功能相同的代码只需要写一次，老师和学生只要继承<code>People</code>即可。</p>
<p>​    使用抽象类时，如果需求发生变化，我们想去掉年龄，增加性别、学历、户籍等信息，只需要修改People一个类即可。如果不使用继承需要修改<code>Student</code>和<code>Teacher</code>两个类。</p>
</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> classroom;<br><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">People</span> </span>&#123;<br>    <span class="hljs-keyword">protected</span> <span class="hljs-keyword">int</span> age;<br>    <span class="hljs-keyword">protected</span> String name;<br>    <span class="hljs-keyword">protected</span> String words;<br>    <span class="hljs-keyword">protected</span> String express;<br><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">People</span><span class="hljs-params">(<span class="hljs-keyword">int</span> age, String name, String words, String express)</span> </span>&#123;<br>        <span class="hljs-keyword">this</span>.age = age;<br>        <span class="hljs-keyword">this</span>.name = name;<br>        <span class="hljs-keyword">this</span>.words = words;<br>        <span class="hljs-keyword">this</span>.express = express;<br>    &#125;<br><br>    <span class="hljs-comment">// 每个人可以做些什么</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doSomething</span><span class="hljs-params">()</span> </span>&#123;<br>        String express = action();<br>        String words = words();<br>        <span class="hljs-keyword">int</span> len = Math.max(express.length(), words.length()) * <span class="hljs-number">2</span>;<br>        StringBuilder sb = <span class="hljs-keyword">new</span> StringBuilder();<br>        String line;<br>        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; len / <span class="hljs-number">2</span>; i++) &#123;<br>            sb.append(<span class="hljs-string">&quot;=&quot;</span>);<br>        &#125;<br>        sb.append(name).append(<span class="hljs-string">&quot;的分割线&quot;</span>);<br>        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; len / <span class="hljs-number">2</span>; i++) &#123;<br>            sb.append(<span class="hljs-string">&quot;=&quot;</span>);<br>        &#125;<br><br>        line = sb.toString();<br>        System.out.println(line);<br>        System.out.println(express);<br>        System.out.print(<span class="hljs-string">&quot;然后说：\&quot;&quot;</span>);<br>        System.out.print(words);<br>        System.out.println(<span class="hljs-string">&quot;。\&quot;&quot;</span>);<br>        System.out.println(line);<br>    &#125;<br><br>    <span class="hljs-comment">// 将会说出的一段话。e.g 我是杨晨</span><br>    <span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">abstract</span> String <span class="hljs-title">words</span><span class="hljs-params">()</span></span>;<br><br>    <span class="hljs-comment">// 做出一个动作。e.g 露出开心的笑容</span><br>    <span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">abstract</span> String <span class="hljs-title">action</span><span class="hljs-params">()</span></span>;<br><br>&#125;<br><br></code></pre></td></tr></table></figure>

<ul>
<li>Teacher类</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> classroom;<br><br><span class="hljs-keyword">import</span> java.util.HashMap;<br><span class="hljs-keyword">import</span> java.util.Map;<br><span class="hljs-keyword">import</span> java.util.function.BiFunction;<br><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Teacher</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">People</span> </span>&#123;<br>    <span class="hljs-keyword">protected</span> String subject;<br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> Map&lt;String, Integer&gt; answer2count = <span class="hljs-keyword">new</span> HashMap&lt;&gt;();<br><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Teacher</span><span class="hljs-params">(<span class="hljs-keyword">int</span> age, String name, String words, String expression)</span> </span>&#123;<br>        <span class="hljs-keyword">this</span>(age, name, words, expression, <span class="hljs-string">&quot;高数&quot;</span>);<br>    &#125;<br><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Teacher</span><span class="hljs-params">(<span class="hljs-keyword">int</span> age, String name, String words, String expression, String subject)</span> </span>&#123;<br>        <span class="hljs-keyword">super</span>(age, name, words, expression);<br>        <span class="hljs-keyword">this</span>.subject = subject;<br>    &#125;<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-function"><span class="hljs-keyword">protected</span> String <span class="hljs-title">words</span><span class="hljs-params">()</span> </span>&#123;<br>        <span class="hljs-keyword">return</span>  words + <span class="hljs-string">&quot;。今天我给大家讲一讲《&quot;</span> +<br>                subject +<br>                <span class="hljs-string">&quot;》&quot;</span>;<br>    &#125;<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-function"><span class="hljs-keyword">protected</span> String <span class="hljs-title">action</span><span class="hljs-params">()</span> </span>&#123;<br>        <span class="hljs-keyword">return</span> name + <span class="hljs-string">&quot;老师&quot;</span> +<br>                express + <span class="hljs-string">&quot;。&quot;</span>;<br>    &#125;<br><br>&#125;<br><br></code></pre></td></tr></table></figure>

<ul>
<li>Student类</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> classroom;<br><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Student</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">People</span> </span>&#123;<br><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Student</span><span class="hljs-params">(<span class="hljs-keyword">int</span> age, String name, String words, String expression)</span> </span>&#123;<br>        <span class="hljs-keyword">super</span>(age, name, words, expression);<br>    &#125;<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-function"><span class="hljs-keyword">protected</span> String <span class="hljs-title">words</span><span class="hljs-params">()</span> </span>&#123;<br>        <span class="hljs-keyword">return</span>  words;<br>    &#125;<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-function"><span class="hljs-keyword">protected</span> String <span class="hljs-title">action</span><span class="hljs-params">()</span> </span>&#123;<br>        <span class="hljs-keyword">return</span> name + <span class="hljs-string">&quot;同学&quot;</span> +<br>                express + <span class="hljs-string">&quot;。&quot;</span>;<br>    &#125;<br><br>&#125;<br><br></code></pre></td></tr></table></figure>

<ul>
<li>Main 主程序</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">import</span> java.util.ArrayList;<br><span class="hljs-keyword">import</span> java.util.List;<br><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;<br>        People mbg = <span class="hljs-keyword">new</span> Teacher(<span class="hljs-number">69</span>, <span class="hljs-string">&quot;马保国&quot;</span>,<br>                <span class="hljs-string">&quot;现在的年轻人不讲武德&quot;</span>, <span class="hljs-string">&quot;捂着红肿的眼睛&quot;</span>,<br>                <span class="hljs-string">&quot;武德&quot;</span>);<br>        People yc = <span class="hljs-keyword">new</span> Teacher(<span class="hljs-number">19</span>, <span class="hljs-string">&quot;杨晨&quot;</span>,<br>                <span class="hljs-string">&quot;我女妆真好看&quot;</span>, <span class="hljs-string">&quot;露出开心的笑容&quot;</span>,<br>                <span class="hljs-string">&quot;女妆的一百零八种技巧&quot;</span>);<br>        People zk = <span class="hljs-keyword">new</span> Student(<span class="hljs-number">21</span>, <span class="hljs-string">&quot;郑开&quot;</span>,<br>                <span class="hljs-string">&quot;杨晨学姐太强力&quot;</span>, <span class="hljs-string">&quot;拍了拍杨晨&quot;</span>);<br>        List&lt;People&gt; peoples = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();<br>        peoples.add(mbg);<br>        peoples.add(yc);<br>        peoples.add(zk);<br>        <span class="hljs-keyword">for</span> (People people : peoples) &#123;<br>            people.doSomething();<br>        &#125;<br>    &#125;<br>&#125;<br><br></code></pre></td></tr></table></figure>

<ul>
<li>输出结果</li>
</ul>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs bash">=====================马保国的分割线=====================<br>马保国老师捂着红肿的眼睛。<br>然后说：<span class="hljs-string">&quot;年轻人不讲武德。今天我给大家讲一讲《武德》。&quot;</span><br>=====================马保国的分割线=====================<br>============================杨晨的分割线============================<br>杨晨老师露出开心的笑容。<br>然后说：<span class="hljs-string">&quot;我女妆真好看。今天我给大家讲一讲《女妆的一百零八种技巧》。&quot;</span><br>============================杨晨的分割线============================<br>==========郑开的分割线==========<br>郑开同学拍了拍杨晨。<br>然后说：<span class="hljs-string">&quot;杨晨学姐太强力。&quot;</span><br>==========郑开的分割线==========<br><br>Process finished with <span class="hljs-built_in">exit</span> code 0<br><br></code></pre></td></tr></table></figure>

<h3 id="多态"><a href="#多态" class="headerlink" title="多态"></a>多态</h3><p>多态存在的<strong>三个必要条件</strong></p>
<ul>
<li>继承</li>
<li>重写</li>
<li>父类引用指向子类对象</li>
</ul>
<p>多态的优点</p>
<ol>
<li><p>消除类型之间的耦合关系</p>
</li>
<li><p>可替换性</p>
</li>
<li><p>可扩充性</p>
</li>
<li><p>接口性</p>
</li>
<li><p>灵活性</p>
</li>
<li><p>简化性</p>
</li>
</ol>
<p>多态是同一个行为具有多个不同表现形式或形态的能力。如：老师和学生都可以<code>doSomething</code>，但是他们do的方式不一样。虽然<code>mbg</code>，<code>yc</code>，<code>zk</code>都是People类型的变量，都调用了同一个方法，但是却有不同的表现形式。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;<br>        People mbg = <span class="hljs-keyword">new</span> Teacher(<span class="hljs-number">69</span>, <span class="hljs-string">&quot;马保国&quot;</span>,<br>                <span class="hljs-string">&quot;现在的年轻人不讲武德&quot;</span>, <span class="hljs-string">&quot;捂着红肿的眼睛&quot;</span>,<br>                <span class="hljs-string">&quot;武德&quot;</span>);<br>        People yc = <span class="hljs-keyword">new</span> Teacher(<span class="hljs-number">19</span>, <span class="hljs-string">&quot;杨晨&quot;</span>,<br>                <span class="hljs-string">&quot;我女妆真好看&quot;</span>, <span class="hljs-string">&quot;露出开心的笑容&quot;</span>,<br>                <span class="hljs-string">&quot;女妆的一百零八种技巧&quot;</span>);<br>       People zk = <span class="hljs-keyword">new</span> Student(<span class="hljs-number">21</span>, <span class="hljs-string">&quot;郑开&quot;</span>,<br>                <span class="hljs-string">&quot;杨晨学姐太强了&quot;</span>, <span class="hljs-string">&quot;拍了拍杨晨&quot;</span>);<br>        List&lt;People&gt; peoples = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();<br>        peoples.add(mbg);<br>        peoples.add(yc);<br>        peoples.add(zk);<br>        <span class="hljs-keyword">for</span> (People people : peoples) &#123;<br>            <span class="hljs-comment">// 尽管有的人是老师，有的人是同学，但我们并不在乎。</span><br>            <span class="hljs-comment">// 因为多态，所以我们可以使用相同的方式，来调用不同的函数。</span><br>            people.doSomething();<br>        &#125;<br>    &#125;<br>&#125;<br><br></code></pre></td></tr></table></figure>

<h2 id="接口"><a href="#接口" class="headerlink" title="接口"></a>接口</h2><p>​    关键字<code>interface</code>，<code>implements</code></p>
<p>​    众所周知，Java的类只能单继承，无论继承的是普通类还是抽象类。但是在庞大的程序中，多继承是不可避免的。为了实现这个功能，Java中引入了接口（Interface）。</p>
<blockquote>
<p>那么问题来了，既然还是要有多继承，为什么不直接设计成可以继承多个类呢？</p>
<p>在C++里，类是可以多继承的，但正是因为它的多继承，让程序员们遇到了很多问题。如菱形继承问题：B继承了A，C继承了A，而D同时继承了B和C，这时D中会出现两个同名的父类A，在使用A时会带来一些问题。</p>
<p><a target="_blank" rel="noopener" href="https://blog.csdn.net/qq_40922859/article/details/89389590">一篇解释这个问题的博客</a></p>
</blockquote>
<ul>
<li><p>接口中可以定义函数和变量</p>
<ol>
<li>接口默认函数是<code>public abstract</code>的。而且接口中的函数只能是public的。</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">Answerable</span> </span>&#123;<br>    <span class="hljs-comment">//去掉这里的public abstract 也是一样的效果</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">void</span> <span class="hljs-title">answerQuestion</span><span class="hljs-params">(String answer)</span></span>; <br>&#125;<br></code></pre></td></tr></table></figure>

<ol start="2">
<li>接口中默认的变量是<code>public static final</code>的。</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">QAndA</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Answerable</span>,<span class="hljs-title">CanAsk</span> </span>&#123;<br>    <span class="hljs-comment">//去掉这里的public static final 也是一样的效果</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> String test = <span class="hljs-string">&quot;这是一个test&quot;</span>; <br>&#125;<br></code></pre></td></tr></table></figure>
</li>
<li><p>接口可以被类用实现，一个类可以实现多个接口。<code>implments</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">//Answerable.java</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">Answerable</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">void</span> <span class="hljs-title">answerQuestion</span><span class="hljs-params">(String answer)</span></span>;<br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">//CanAsk.java</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">CanAsk</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">askQuestion</span><span class="hljs-params">(Answerable answerable, String question)</span></span>;<br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">//People.java</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">People</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">CanAsk</span>, <span class="hljs-title">Answerable</span> </span>&#123;<br>    <span class="hljs-comment">//...</span><br>    <span class="hljs-comment">//因为是抽象类，所以即使不实现接口中定义的函数也可以。</span><br><br>&#125;<br></code></pre></td></tr></table></figure>
</li>
<li><p>接口可以继承多个接口。<code>extends</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">QAndA</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Answerable</span>,<span class="hljs-title">CanAsk</span> </span>&#123;<br>    <span class="hljs-comment">//QAndA接口中有在Answerable定义的抽象方法 answerQuestion和CanAsk中定义的抽象方法askQuetion</span><br>    <span class="hljs-comment">// 可以定义新的方法</span><br>&#125;<br></code></pre></td></tr></table></figure>

</li>
</ul>
<blockquote>
<p>有了接口也就解决了之前说的多继承的问题。即使不同的接口有同名的函数，因为都没有实现，所以也就不会有菱形继承的问题。</p>
</blockquote>
<ul>
<li><p>接口与抽象类：</p>
<ol>
<li><p><code>static</code>与<code>default</code></p>
<p>在jdk1.8之后，增加了这两个特性。在接口中可以使用<code>static</code>和<code>default</code>来修饰方法，当使用这两个关键字来修饰函数时，函数就不能被<code>abstract</code>修饰了。</p>
<p>接口中可以定义静态函数，使用方式和类没有区别。需要在接口中定义函数实现。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">InterfaceA</span> </span>&#123;<br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 静态方法</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">showStatic</span><span class="hljs-params">()</span> </span>&#123;<br>        System.out.println(<span class="hljs-string">&quot;InterfaceA++showStatic&quot;</span>);<br>    &#125;<br>&#125;<br><br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Test</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;<br>        InterfaceA.show();<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs bash"><span class="hljs-comment"># 结果</span><br>InterfaceA++showStatic<br></code></pre></td></tr></table></figure>

<p>在类中，<code>default</code>是默认的访问修饰符，不需要写出。但是同时<code>default</code>也是Java的关键字，在接口中使用它修饰方法，表示该方法需要一个默认的实现。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">InterfaceA</span> </span>&#123;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 静态方法</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">showStatic</span><span class="hljs-params">()</span> </span>&#123;<br>        System.out.println(<span class="hljs-string">&quot;InterfaceA++showStatic&quot;</span>);<br>    &#125;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 默认方法</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-function"><span class="hljs-keyword">default</span> <span class="hljs-keyword">void</span> <span class="hljs-title">showDefault</span><span class="hljs-params">()</span> </span>&#123;<br>        System.out.println(<span class="hljs-string">&quot;InterfaceA ++showDefault&quot;</span>);<br>    &#125;<br><br>&#125;<br><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">InterfaceAImpl</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">InterfaceA</span></span>&#123;<br>	<br><br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Test</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;<br>        InterfaceA.showStatic();<br>        <span class="hljs-keyword">new</span> InterfaceAImpl().showDefault();<br>    &#125;<br>&#125;<br><br></code></pre></td></tr></table></figure>

<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs bash"><span class="hljs-comment"># 结果</span><br>InterfaceA++showStatic<br>InterfaceA ++showDefault<br></code></pre></td></tr></table></figure>

<p>子类可以重写接口的default函数</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">InterfaceAImpl</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">InterfaceA</span></span><br><span class="hljs-class">    /**</span><br><span class="hljs-class">     * </span><br><span class="hljs-class">     * 跟接口<span class="hljs-title">default</span>方法一致,但不能再加<span class="hljs-title">default</span>修饰符</span><br><span class="hljs-class">     */</span><br><span class="hljs-class">    @<span class="hljs-title">Override</span></span><br><span class="hljs-class">    <span class="hljs-title">public</span> <span class="hljs-title">void</span> <span class="hljs-title">showDefault</span>()</span>&#123;<br>        System.out.println(<span class="hljs-string">&quot;InterfaceAImpl++ defaultShow&quot;</span>);<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<blockquote>
<p>既然在jdk1.8之后，接口可以有默认的函数实现了，那之前的菱形继承的问题，不就又出现了吗。在Java中提供了解决方案，只要出现了冲突，那么子类就必须要重写这个函数。</p>
</blockquote>
</li>
<li><p>他们都不可以被实例化</p>
</li>
<li><p>一个类可以实现多个接口，但只能继承一个类。</p>
</li>
</ol>
</li>
</ul>
<h3 id="匿名内部类与Lambda表达式"><a href="#匿名内部类与Lambda表达式" class="headerlink" title="匿名内部类与Lambda表达式"></a>匿名内部类与Lambda表达式</h3><ul>
<li><p>匿名内部类</p>
<p>在类的内部，我们依旧可以定义类。这样的类叫做<strong>内部类</strong>。其中有一种特殊的内部类叫做<strong>匿名内部类</strong>。</p>
</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">//定义一个接口</span><br><span class="hljs-keyword">package</span> anoymous;<br><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">Animal</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">speak</span><span class="hljs-params">()</span></span>;<br>    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">eat</span><span class="hljs-params">()</span></span>;<br><br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> anoymous;<br><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AnonymousMain</span> </span>&#123;<br>    <span class="hljs-comment">//内部类</span><br>    <span class="hljs-keyword">static</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AnimalImpl</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Animal</span></span>&#123;<br>        <span class="hljs-meta">@Override</span><br>        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">speak</span><span class="hljs-params">()</span> </span>&#123;<br>            <br>        &#125;<br>        <span class="hljs-meta">@Override</span><br>        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">eat</span><span class="hljs-params">()</span> </span>&#123;<br><br>        &#125;<br>    &#125;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;<br>        Animal animalImpl = <span class="hljs-keyword">new</span> AnimalImpl();<br>        <span class="hljs-comment">// 匿名内部类，匿名内部类实际上也创建了一个新的类，我们需要实现接口中的抽象函数。但是匿名内部类只能实例化这一次。</span><br>        <span class="hljs-comment">// 除了接口，抽象类也可以通过匿名内部类的方式创建实例。</span><br>        Animal anonymousAnimal = <span class="hljs-keyword">new</span> Animal() &#123;<br>            <span class="hljs-meta">@Override</span><br>            <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">speak</span><span class="hljs-params">()</span> </span>&#123;<br><br>            &#125;<br><br>            <span class="hljs-meta">@Override</span><br>            <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">eat</span><span class="hljs-params">()</span> </span>&#123;<br><br>            &#125;<br>        &#125;;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<ul>
<li><p>Lambda表达式</p>
<p>当接口只有一个函数时，可以用Lambda表达式替换匿名内部类。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> anoymous;<br><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">SingleFunctionInterface</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">function</span><span class="hljs-params">(<span class="hljs-keyword">int</span> a,<span class="hljs-keyword">int</span> b)</span></span>;<br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> anoymous;<br><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AnonymousMain</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;<br>        <span class="hljs-comment">// 匿名内部类</span><br>        SingleFunctionInterface singleFunctionInterface =<br>            <span class="hljs-keyword">new</span> SingleFunctionInterface() &#123;<br>            <span class="hljs-meta">@Override</span><br>            <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">function</span><span class="hljs-params">(<span class="hljs-keyword">int</span> a, <span class="hljs-keyword">int</span> b)</span> </span>&#123;<br>                System.out.println(a + b);<br>                <span class="hljs-keyword">return</span> a + b;<br>            &#125;<br>        &#125;;<br>        <span class="hljs-comment">// Lambda表达式</span><br>        <span class="hljs-comment">// ()括号中的参数对应接口中函数的参数列表。</span><br>        <span class="hljs-comment">// -&gt;剪头后&#123;&#125;花括号内的内容为实现的方法体</span><br>        SingleFunctionInterface singleFunctionInterface2 =<br>                (a, b) -&gt; &#123;<br>                    System.out.println(a + b);<br>                    <span class="hljs-keyword">return</span> a + b;<br>        &#125;;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

</li>
</ul>
<h2 id="泛型"><a href="#泛型" class="headerlink" title="泛型"></a>泛型</h2><p>Java泛型（<code>generics</code>）是JDK 5中引入的一个新特性，<strong>泛型提供了编译时类型安全监测机制</strong>，该机制允许程序员在编译时监测非法的类型（编译后与泛型相关的信息会被擦掉，即<strong>类型擦除</strong>）。使用泛型机制编写的程序代码要比那些杂乱地使用<code>Object</code>变量，然后再进行强制类型转换的代码具有<strong>更好的安全性和可读性</strong>。泛型对于集合类尤其有用，例如，<code>ArrayList</code>就是一个无处不在的集合类。</p>
<p><strong>泛型的本质是参数化类型</strong>，也就是所操作的数据类型被指定为一个参数。</p>
<blockquote>
<p>我们为什么需要泛型？</p>
<p>假如我们需要一个类在使用上和数组的使用几乎无异，但是它可以自动扩展长度.</p>
<p>当添加的元素数量超过数组的长度时,这个类会新建一个长度为原本长度2倍的数组来替换原本的数组.</p>
<p>这时我们需要创建一个类,它拥有一个数组类型的成员变量,像这样.</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> generic;<br><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">StringsClass</span> </span>&#123;<br><span class="hljs-keyword">private</span> String[] data;<br><br><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">StringsClass</span><span class="hljs-params">(String[] data)</span> </span>&#123;<br>  <span class="hljs-keyword">this</span>.data = data;<br>&#125;<br><br><span class="hljs-keyword">public</span> String[] getData() &#123;<br>  <span class="hljs-keyword">return</span> data;<br>&#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>但是数组创建时我们可以任意指定一种类型.如果我们需要整数类型,那就要这样:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> generic;<br><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">IntegersClass</span> </span>&#123;<br><span class="hljs-keyword">private</span> Integer[] data;<br><br><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">IntegersClass</span><span class="hljs-params">(Integer[] data)</span> </span>&#123;<br>  <span class="hljs-keyword">this</span>.data = data;<br>&#125;<br><br><span class="hljs-keyword">public</span> Integer[] getData() &#123;<br>  <span class="hljs-keyword">return</span> data;<br>&#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>这样不仅代码会高度重复,而且我每自定义一个新的类型，都需要再写一个类，再重复一遍代码。</p>
<p>那不如：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> generic;<br><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ObjectsClass</span> </span>&#123;<br> <span class="hljs-keyword">private</span> Object[] data;<br><br> <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">ObjectsClass</span><span class="hljs-params">(Object[] data)</span> </span>&#123;<br>     <span class="hljs-keyword">this</span>.data = data;<br> &#125;<br><br> <span class="hljs-keyword">public</span> Object[] getData() &#123;<br>     <span class="hljs-keyword">return</span> data;<br> &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>因为Java中，所有类的父类都是Object，这样不管你要什么类型都可以了。我们只需要ObjectsClass一个类即可维护所有类型的数组。</p>
<p>但是这样使用时需要强制类型转换，而且在使用时我也无法得知，某个ObjectsClass类的实例到底存了什么类型的变量。data变量很可能存了不同类型的变量，在实际使用时依旧存在很多问题。</p>
<p>所以我们需要一种机制来解决这个问题，它就是<strong>泛型（<code>generics</code>）</strong></p>
</blockquote>
<h3 id="泛型类"><a href="#泛型类" class="headerlink" title="泛型类"></a>泛型类</h3><p>在类名后增加&lt;T&gt;,就是泛型类.其中T是泛型变量。我们也可以指定多个泛型变量，而且可以任意命名（必须符合java变量的命名规范），比如：&lt;T,K,M,O&gt;，&lt;FIRST,SECOND&gt;。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> generic;<br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">GenericClass</span>&lt;<span class="hljs-title">T</span>&gt; </span>&#123;<br>    <span class="hljs-keyword">private</span> T[] data;<br><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">GenericClass</span><span class="hljs-params">(T[] data)</span> </span>&#123;<br>        <span class="hljs-keyword">this</span>.data = data;<br>    &#125;<br><br>    <span class="hljs-keyword">public</span> T[] getData() &#123;<br>        <span class="hljs-keyword">return</span> data;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> generic;<br><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">GenericMain</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;<br>        Integer[] integers = &#123;<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>&#125;;<br>        <span class="hljs-comment">//&lt;&gt;我们通过这个尖括号来指定类型。我们可以认为它是类的参数，在使用这个类的时候我们需要传入参数，当传入Integer类型时，GenericClass中的T就是Integer。</span><br>        GenericClass&lt;Integer&gt; integerGenericClass = <span class="hljs-keyword">new</span> GenericClass&lt;&gt;(integers);<br>        String[] strings = &#123;<span class="hljs-string">&quot;a&quot;</span>,<span class="hljs-string">&quot;b&quot;</span>,<span class="hljs-string">&quot;ccc&quot;</span>,<span class="hljs-string">&quot;defg&quot;</span>&#125;;<br>        GenericClass&lt;String&gt; stringGenericClass = <span class="hljs-keyword">new</span> GenericClass&lt;&gt;(strings);<br>        <span class="hljs-comment">// 如果不指定类型T 就是Object类型，但是不推荐这样使用。</span><br>        GenericClass genericClass = <span class="hljs-keyword">new</span> GenericClass(integers);<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<h3 id="泛型接口"><a href="#泛型接口" class="headerlink" title="泛型接口"></a>泛型接口</h3><p>定义泛型接口的方式和定义泛型类很相近。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> generic;<br><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">Generator</span>&lt;<span class="hljs-title">T</span>&gt; </span>&#123;<br><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> T <span class="hljs-title">next</span><span class="hljs-params">()</span></span>;<br><br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">//继承了泛型接口，但是是普通类</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">FruitGenerator</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Generator</span>&lt;<span class="hljs-title">String</span>&gt; </span>&#123;<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">next</span><span class="hljs-params">()</span> </span>&#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;Fruit&quot;</span>;<br>    &#125;<br><br>&#125;<br><span class="hljs-comment">//继承了泛型接口，但是是泛型类</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">FruitGenerator</span>&lt;<span class="hljs-title">T</span>&gt; <span class="hljs-keyword">implements</span> <span class="hljs-title">Generator</span>&lt;<span class="hljs-title">T</span>&gt; </span>&#123;<br><br>    <span class="hljs-keyword">private</span> T next;<br><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">FruitGenerator</span><span class="hljs-params">(T next)</span> </span>&#123;<br>        <span class="hljs-keyword">this</span>.next = next;<br>    &#125;<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> T <span class="hljs-title">next</span><span class="hljs-params">()</span> </span>&#123;<br>        <span class="hljs-keyword">return</span> next;<br>    &#125;<br><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span></span>&#123;<br>        FruitGenerator&lt;String&gt; fruit = <span class="hljs-keyword">new</span> FruitGenerator&lt;&gt;(<span class="hljs-string">&quot;Fruit&quot;</span>);<br>        System.out.println(fruit.next);<br>    &#125;<br><br>&#125;<br></code></pre></td></tr></table></figure>

<h3 id="泛型方法"><a href="#泛型方法" class="headerlink" title="泛型方法"></a>泛型方法</h3><p>定义泛型方法时，<strong>尖括号和类型变量</strong>需要放在<strong>修饰符</strong>和返回类型之间。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> generic;<br><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">GenericMain</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;<br>        Integer[] integers = &#123;<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>&#125;;<br>        GenericClass&lt;Integer&gt; integerGenericClass = <span class="hljs-keyword">new</span> GenericClass&lt;&gt;(integers);<br>        String[] strings = &#123;<span class="hljs-string">&quot;a&quot;</span>, <span class="hljs-string">&quot;b&quot;</span>, <span class="hljs-string">&quot;ccc&quot;</span>, <span class="hljs-string">&quot;defg&quot;</span>&#125;;<br>        GenericClass&lt;String&gt; stringGenericClass = <span class="hljs-keyword">new</span> GenericClass&lt;&gt;(strings);<br>        GenericClass genericClass = <span class="hljs-keyword">new</span> GenericClass(integers);<br>        print(integerGenericClass.getData());<br>        print(stringGenericClass.getData());<br>    &#125;<br>	<span class="hljs-comment">// 在返回类型前指定泛型&lt;T&gt; </span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> &lt;T&gt; <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">print</span><span class="hljs-params">(T[] ts)</span> </span>&#123;<br>        <span class="hljs-keyword">for</span> (T t : ts) &#123;<br>            System.out.print(t + <span class="hljs-string">&quot; &quot;</span>);<br>        &#125;<br>        System.out.println();<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<h3 id="常用的数据结构"><a href="#常用的数据结构" class="headerlink" title="常用的数据结构"></a>常用的数据结构</h3><h4 id="集合（Collection）"><a href="#集合（Collection）" class="headerlink" title="集合（Collection）"></a>集合（Collection）</h4><p><strong>Collection</strong>是Java中的一个接口，它定义了容器应有的方法，如添加元素、删除元素、遍历元素、清空等等。它有很多不同的实现。容器要容纳某一种类型的元素，所以在使用容器时需要用到泛型。</p>
<ul>
<li><p>常用方法</p>
<p><code>Collection</code>为所有容器定义了元素操作，常用的有：</p>
<ol>
<li><p><code>add(E e)</code>方法添加元素</p>
</li>
<li><p><code>remove()</code>方法删除元素</p>
</li>
<li><p><code>clear()</code>方法清空容器</p>
</li>
</ol>
</li>
</ul>
<p><code>Collection</code>有很多不同的实现：</p>
<h5 id="列表（List）"><a href="#列表（List）" class="headerlink" title="列表（List）"></a>列表（List）</h5><p>​    数组相似。但<code>List</code>是一个<strong>接口</strong>，不能被实例化，需要使用<code>ArrayList</code>或<code>LinkedList</code>等。</p>
<h5 id="集合（Set）"><a href="#集合（Set）" class="headerlink" title="集合（Set）"></a>集合（Set）</h5><p>​    集合中不能有重复的元素。同样<code>Set</code>也是一个接口，需要使用<code>HashSet</code>或<code>SortedSet</code>等。</p>
<h5 id="队列（Queue）"><a href="#队列（Queue）" class="headerlink" title="队列（Queue）"></a>队列（Queue）</h5><p>​    类似列表，但是对容器的操作方式进行了限制，只能将新元素放在最后，只能拿出最早放进去的元素。具有<strong>先进先出</strong>的性质，像排队一样。<code>Queue</code>也是一个接口，需要使用<code>ArrayQueue</code>等。</p>
<h5 id="栈（Stack）"><a href="#栈（Stack）" class="headerlink" title="栈（Stack）"></a>栈（Stack）</h5><p>​    类似队列，但是只能将新元素放在前面，且只能拿出最新放进去的元素。具有<strong>后进先出</strong>的性质。</p>
<h4 id="映射（Map）"><a href="#映射（Map）" class="headerlink" title="映射（Map）"></a>映射（Map）</h4><p>​    <code>Map</code>是一个接口，但<code>Map</code>并<strong>不是</strong><code>Collection</code>的子接口。</p>
<p>​    <code>Map</code>中存储的是键值对&lt;KEY,VALUE&gt;，我们可以通过键拿到对应的值，即键和值构成了映射关系。</p>
<p>​    <code>Map</code>是接口，我们可以用<code>HashMap</code>来实例化。</p>
<ul>
<li><p>常用的方法</p>
<p>Map实例可以通过:</p>
<ol>
<li><code>V put(K k, V v)</code>向map中存入一个键值对，<code>K</code>为键，<code>V</code>为值，返回之前这个键对应的值。</li>
<li><code>V remove(Object key)</code>根据键移除map中的键值对。</li>
<li><code>V get(Object o)</code>根据键查找值。</li>
<li><code>Set&lt;K&gt; keySet()</code>获取map的键的集合</li>
<li><code>Collection&lt;V&gt; values()</code>获取map的值的集合</li>
<li><code>Set&lt;Map.Entry&lt;K, V&gt;&gt; entrySet()</code>获取键值对集合</li>
<li><code>V replace(K key, V value)</code>将key对应的值替换为参数value</li>
</ol>
</li>
</ul>
<h3 id="一个例子"><a href="#一个例子" class="headerlink" title="一个例子"></a>一个例子</h3><p>​    在之前People的demo基础上，增加一些代码。我们要定义一间教室，教室里有很多人<code>People</code>，人要可以问问题，还可以回答问题，人们可以在教室里进行讨论。我的帮手<strong>小明</strong>决定帮我完成<code>Classroom</code>类的定义，而我去完善人的定义。</p>
<p>​    但是现在，我们的“人”并不会问问题，也不会回答问题，<strong>小明</strong>也不知道我将会用什么样的方式实现这个功能。为了能够尽快开始工作，我们协商了两个接口<code>Answerable</code>和<code>CanAsk</code>，我们不需要修改什么代码，只要让<code>People</code>类实现这两个接口就定义好了”人”需要怎么问问题，怎么回答问题。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> classroom;<br><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">Answerable</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">void</span> <span class="hljs-title">answerQuestion</span><span class="hljs-params">(String answer)</span></span>;<br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> classroom;<br><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">CanAsk</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">askQuestion</span><span class="hljs-params">(Answerable answerable, String question)</span></span>;<br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">People</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">CanAsk</span>, <span class="hljs-title">Answerable</span> </span>&#123;<br>    <span class="hljs-comment">//...</span><br>&#125;<br></code></pre></td></tr></table></figure>

<p>​    此时，我和<strong>小明</strong>就可以各自开始干各自的活。他写他的<code>Classroom</code>，我去完善<code>Teacher</code>和<code>Student</code>。而<code>Answerable</code>和<code>CanAsk</code>以及<code>People</code>在我们完工之前不能<strong>私自</strong>进行任何改动，这三块代码已经成为了我和<strong>小明</strong>任务对接的接口，它成为了一个<strong>不能轻易改变</strong>的协议，因为我们在完成各自的任务时<strong>都需要使用</strong>到这三份代码。</p>
<p>三天后，任务完成了，即使这三天我们没有进行任何沟通，代码也合并得十分完美，Perfect!</p>
<p>完成后的代码：</p>
<ul>
<li><p>Classroom.java</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> classroom;<br><br><span class="hljs-keyword">import</span> java.util.*;<br><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Classroom</span> </span>&#123;<br>    <span class="hljs-comment">// 人不能有重复，所以使用set。重写了people类的equals 和 hashcode函数，集合才可以更合理地查重</span><br>    <span class="hljs-keyword">private</span> Set&lt;People&gt; peoples = <span class="hljs-keyword">new</span> HashSet&lt;&gt;();<br>    <span class="hljs-keyword">private</span> String name;<br>    <span class="hljs-comment">// 记录题目到答案的映射。存储&lt;题目，答案&gt;键值对。</span><br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> Map&lt;String, String&gt; question2answer = <span class="hljs-keyword">new</span> HashMap&lt;&gt;();<br><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Classroom</span><span class="hljs-params">(String name)</span> </span>&#123;<br>        <span class="hljs-keyword">this</span>.name = name;<br>        <span class="hljs-comment">//添加默认题库</span><br>        question2answer.put(<span class="hljs-string">&quot;1+1=?&quot;</span>, <span class="hljs-string">&quot;2&quot;</span>);<br>        question2answer.put(<span class="hljs-string">&quot;杨晨学姐美不美?&quot;</span>, <span class="hljs-string">&quot;美！&quot;</span>);<br>    &#125;<br><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getName</span><span class="hljs-params">()</span> </span>&#123;<br>        <span class="hljs-keyword">return</span> name;<br>    &#125;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 添加问题</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> question 问题</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> answer 答案</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@return</span> 教室</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> Classroom <span class="hljs-title">addQA</span><span class="hljs-params">(String question,String answer)</span></span>&#123;<br>        question2answer.put(question,answer);<br>        <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>;<br>    &#125;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 给教室添加人</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> people 人</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@return</span> 教室</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> Classroom <span class="hljs-title">addPeople</span><span class="hljs-params">(People people)</span> </span>&#123;<br>        peoples.add(people);<br>        <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>;<br>    &#125;<br><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">addPeople</span><span class="hljs-params">(List&lt;People&gt; peoples)</span> </span>&#123;<br>        <span class="hljs-keyword">this</span>.peoples.addAll(peoples);<br>    &#125;<br><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">addPeople</span><span class="hljs-params">(People... peoples)</span> </span>&#123;<br>        <span class="hljs-keyword">this</span>.peoples.addAll(Arrays.asList(peoples));<br>    &#125;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 提供答案查询功能</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> question</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@return</span></span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> String <span class="hljs-title">getAnswer</span><span class="hljs-params">(String question)</span> </span>&#123;<br>        <span class="hljs-keyword">return</span> question2answer.get(question);<br>    &#125;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 开始讨论</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">discuss</span><span class="hljs-params">()</span> </span>&#123;<br>        <span class="hljs-keyword">int</span> askIndex, answerIndex, questionIndex;<br>        <span class="hljs-comment">// 将人和问题转成数组</span><br>        People[] peopleArray = <span class="hljs-keyword">new</span> People[peoples.size()];<br>        String[] questionArray = <span class="hljs-keyword">new</span> String[question2answer.keySet().size()];<br>        question2answer.keySet().toArray(questionArray);<br>        peoples.toArray(peopleArray);<br>        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> k = <span class="hljs-number">0</span>; k &lt; <span class="hljs-number">5</span>; k++) &#123;<br>            <span class="hljs-comment">//通过Math.random取随机数得到随机的索引值。</span><br>            askIndex = (<span class="hljs-keyword">int</span>) (Math.random() * peopleArray.length);<br>            answerIndex = (<span class="hljs-keyword">int</span>) (Math.random() * peopleArray.length);<br>            <span class="hljs-keyword">while</span> (answerIndex == askIndex) &#123;<br>                answerIndex = (<span class="hljs-keyword">int</span>) (Math.random() * peopleArray.length);<br>            &#125;<br>            questionIndex = (<span class="hljs-keyword">int</span>) (Math.random() * questionArray.length);<br>            <span class="hljs-comment">//随机选择一个人随机问另一个人随机一个问题</span><br>            peopleArray[askIndex].askQuestion(peopleArray[answerIndex], questionArray[questionIndex]);<br>        &#125;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>
</li>
<li><p>People.java</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> classroom;<br><br><span class="hljs-keyword">import</span> java.util.Objects;<br><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">People</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">CanAsk</span>, <span class="hljs-title">Answerable</span> </span>&#123;<br>    <span class="hljs-keyword">protected</span> <span class="hljs-keyword">int</span> age;<br>    <span class="hljs-keyword">protected</span> String name;<br>    <span class="hljs-keyword">protected</span> String words;<br>    <span class="hljs-keyword">protected</span> String action;<br><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">People</span><span class="hljs-params">(<span class="hljs-keyword">int</span> age, String name, String words, String action)</span> </span>&#123;<br>        <span class="hljs-keyword">this</span>.age = age;<br>        <span class="hljs-keyword">this</span>.name = name;<br>        <span class="hljs-keyword">this</span>.words = words;<br>        <span class="hljs-keyword">this</span>.action = action;<br>    &#125;<br><br>    <span class="hljs-comment">// 每个人可以做些什么</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doSomething</span><span class="hljs-params">()</span> </span>&#123;<br>        String action = action();<br>        String words = words();<br>        <span class="hljs-keyword">int</span> len = Math.max(action.length(), words.length()) * <span class="hljs-number">2</span>;<br>        StringBuilder sb = <span class="hljs-keyword">new</span> StringBuilder();<br>        String line;<br>        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; len / <span class="hljs-number">2</span>; i++) &#123;<br>            sb.append(<span class="hljs-string">&quot;=&quot;</span>);<br>        &#125;<br>        sb.append(name).append(<span class="hljs-string">&quot;的分割线&quot;</span>);<br>        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; len / <span class="hljs-number">2</span>; i++) &#123;<br>            sb.append(<span class="hljs-string">&quot;=&quot;</span>);<br>        &#125;<br><br>        line = sb.toString();<br>        System.out.println(line);<br>        System.out.println(action);<br>        System.out.print(<span class="hljs-string">&quot;然后说：\&quot;&quot;</span>);<br>        System.out.print(words);<br>        System.out.println(<span class="hljs-string">&quot;。\&quot;&quot;</span>);<br>        System.out.println(line);<br>    &#125;<br><br>    <span class="hljs-comment">// 将会说出的一段话。e.g 我是杨晨</span><br>    <span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">abstract</span> String <span class="hljs-title">words</span><span class="hljs-params">()</span></span>;<br><br>    <span class="hljs-comment">// 做出一个动作。e.g 露出开心的笑容</span><br>    <span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">abstract</span> String <span class="hljs-title">action</span><span class="hljs-params">()</span></span>;<br><br>    <span class="hljs-comment">//为了Set可以更好的判断people是否相同，重写Object类的equals和hashCode函数</span><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">equals</span><span class="hljs-params">(Object o)</span> </span>&#123;<br>        <span class="hljs-keyword">if</span> (<span class="hljs-keyword">this</span> == o) <span class="hljs-keyword">return</span> <span class="hljs-keyword">true</span>;<br>        <span class="hljs-keyword">if</span> (o == <span class="hljs-keyword">null</span> || getClass() != o.getClass()) <span class="hljs-keyword">return</span> <span class="hljs-keyword">false</span>;<br>        People people = (People) o;<br>        <span class="hljs-keyword">return</span> age == people.age &amp;&amp;<br>                Objects.equals(name, people.name) &amp;&amp;<br>                Objects.equals(words, people.words) &amp;&amp;<br>                Objects.equals(action, people.action);<br>    &#125;<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">hashCode</span><span class="hljs-params">()</span> </span>&#123;<br>        <span class="hljs-keyword">return</span> Objects.hash(age, name, words, action);<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>
</li>
<li><p>Student.java</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> classroom;<br><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Student</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">People</span> </span>&#123;<br><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Student</span><span class="hljs-params">(<span class="hljs-keyword">int</span> age, String name, String words, String expression)</span> </span>&#123;<br>        <span class="hljs-keyword">super</span>(age, name, words, expression);<br>    &#125;<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-function"><span class="hljs-keyword">protected</span> String <span class="hljs-title">words</span><span class="hljs-params">()</span> </span>&#123;<br>        <span class="hljs-keyword">return</span>  words;<br>    &#125;<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-function"><span class="hljs-keyword">protected</span> String <span class="hljs-title">action</span><span class="hljs-params">()</span> </span>&#123;<br>        <span class="hljs-keyword">return</span> name + <span class="hljs-string">&quot;同学&quot;</span> +<br>                action + <span class="hljs-string">&quot;。&quot;</span>;<br>    &#125;<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">answerQuestion</span><span class="hljs-params">(String answer)</span> </span>&#123;<br>        System.out.println(<span class="hljs-string">&quot;A--Student &quot;</span> + name + <span class="hljs-string">&quot; :&quot;</span>);<br>        <span class="hljs-keyword">if</span>(answer==<span class="hljs-keyword">null</span>)&#123;<br>            System.out.println(<span class="hljs-string">&quot;我也不知道&quot;</span>);<br>            <span class="hljs-keyword">return</span>;<br>        &#125;<br>        <span class="hljs-keyword">double</span> random = Math.random();<br>        <span class="hljs-comment">//假设学生有50%的概率知道答案。</span><br>        <span class="hljs-keyword">if</span> (random &gt;= <span class="hljs-number">0.5</span>) &#123;<br>            System.out.println(<span class="hljs-string">&quot;答案我知道，是：&quot;</span> + answer);<br>        &#125; <span class="hljs-keyword">else</span> &#123;<br>            System.out.println(<span class="hljs-string">&quot;答案是...我也不知道&quot;</span>);<br>        &#125;<br>    &#125;<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">askQuestion</span><span class="hljs-params">(Answerable answerable, String question)</span> </span>&#123;<br>        System.out.println(<span class="hljs-string">&quot;Q--Student &quot;</span> + name + <span class="hljs-string">&quot; :&quot;</span>);<br>        System.out.println(<span class="hljs-string">&quot;我想问个问题：&quot;</span> + question);<br>        <span class="hljs-comment">//通知那个人（answerable）该回答问题了。</span><br>        answerable.answerQuestion(Classroom.getAnswer(question));<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>
</li>
<li><p>Teacher.java</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> classroom;<br><br><span class="hljs-keyword">import</span> java.util.HashMap;<br><span class="hljs-keyword">import</span> java.util.Map;<br><span class="hljs-keyword">import</span> java.util.function.BiFunction;<br><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Teacher</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">People</span> </span>&#123;<br>    <span class="hljs-keyword">protected</span> String subject;<br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> Map&lt;String, Integer&gt; answer2count = <span class="hljs-keyword">new</span> HashMap&lt;&gt;();<br><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Teacher</span><span class="hljs-params">(<span class="hljs-keyword">int</span> age, String name, String words, String expression)</span> </span>&#123;<br>        <span class="hljs-keyword">this</span>(age, name, words, expression, <span class="hljs-string">&quot;高数&quot;</span>);<br>    &#125;<br><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Teacher</span><span class="hljs-params">(<span class="hljs-keyword">int</span> age, String name, String words, String expression, String subject)</span> </span>&#123;<br>        <span class="hljs-keyword">super</span>(age, name, words, expression);<br>        <span class="hljs-keyword">this</span>.subject = subject;<br>    &#125;<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-function"><span class="hljs-keyword">protected</span> String <span class="hljs-title">words</span><span class="hljs-params">()</span> </span>&#123;<br>        <span class="hljs-keyword">return</span> words + <span class="hljs-string">&quot;。今天我给大家讲一讲《&quot;</span> +<br>                subject +<br>                <span class="hljs-string">&quot;》&quot;</span>;<br>    &#125;<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-function"><span class="hljs-keyword">protected</span> String <span class="hljs-title">action</span><span class="hljs-params">()</span> </span>&#123;<br>        <span class="hljs-keyword">return</span> name + <span class="hljs-string">&quot;老师&quot;</span> +<br>                action + <span class="hljs-string">&quot;。&quot;</span>;<br>    &#125;<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">answerQuestion</span><span class="hljs-params">(String answer)</span> </span>&#123;<br>        System.out.println(<span class="hljs-string">&quot;A--Teacher &quot;</span> + name + <span class="hljs-string">&quot; :&quot;</span>);<br>        <span class="hljs-keyword">if</span> (answer == <span class="hljs-keyword">null</span>) &#123;<br>            System.out.println(<span class="hljs-string">&quot;我也不知道&quot;</span>);<br>            <span class="hljs-keyword">return</span>;<br>        &#125;<br>        Integer count = answer2count.get(answer);<br>        <span class="hljs-keyword">if</span> (count != <span class="hljs-keyword">null</span> &amp;&amp; count &gt; <span class="hljs-number">1</span>) &#123;<br>            System.out.println(<span class="hljs-string">&quot;这道题我已经讲过&quot;</span> + count + <span class="hljs-string">&quot;次了！&quot;</span>);<br>        &#125;<br>        System.out.println(<span class="hljs-string">&quot;这道题的答案是：&quot;</span> + answer);<br>        answer2count.merge(answer, <span class="hljs-number">1</span>,<br>                <span class="hljs-comment">//匿名内部类</span><br>                <span class="hljs-keyword">new</span> BiFunction&lt;Integer, Integer, Integer&gt;() &#123;<br>                    <span class="hljs-meta">@Override</span><br>                    <span class="hljs-function"><span class="hljs-keyword">public</span> Integer <span class="hljs-title">apply</span><span class="hljs-params">(Integer integer, Integer integer2)</span> </span>&#123;<br>                        <span class="hljs-keyword">return</span> integer + integer2;<br>                    &#125;<br>                &#125;);<br>        <span class="hljs-comment">//Lambda表达式</span><br><span class="hljs-comment">//        answer2count.merge(answer, 1,</span><br><span class="hljs-comment">//                (integer, integer2) -&gt; integer + integer2);</span><br>        <span class="hljs-comment">//使用相同的函数代替Lambda表达式</span><br><span class="hljs-comment">//        answer2count.merge(answer, 1,</span><br><span class="hljs-comment">//                Integer::sum);</span><br><br><br>    &#125;<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">askQuestion</span><span class="hljs-params">(Answerable answerable, String question)</span> </span>&#123;<br>        System.out.println(<span class="hljs-string">&quot;Q--Teacher &quot;</span> + name + <span class="hljs-string">&quot; :&quot;</span>);<br>        System.out.println(<span class="hljs-string">&quot;问题是：&quot;</span> + question);<br>        <span class="hljs-comment">//通知那个人（answerable）该回答问题了。</span><br>        answerable.answerQuestion(Classroom.getAnswer(question));<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>
</li>
<li><p>Main.java</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">import</span> classroom.*;<br><br><span class="hljs-keyword">import</span> java.util.ArrayList;<br><span class="hljs-keyword">import</span> java.util.List;<br><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;<br>        People mbg = <span class="hljs-keyword">new</span> Teacher(<span class="hljs-number">69</span>, <span class="hljs-string">&quot;马保国&quot;</span>,<br>                <span class="hljs-string">&quot;年轻人不讲武德&quot;</span>, <span class="hljs-string">&quot;捂着红肿的眼睛&quot;</span>,<br>                <span class="hljs-string">&quot;武德&quot;</span>);<br>        People yc = <span class="hljs-keyword">new</span> Teacher(<span class="hljs-number">19</span>, <span class="hljs-string">&quot;杨晨&quot;</span>,<br>                <span class="hljs-string">&quot;我女妆真好看&quot;</span>, <span class="hljs-string">&quot;露出开心的笑容&quot;</span>,<br>                <span class="hljs-string">&quot;女妆的一百零八种技巧&quot;</span>);<br>        People zk = <span class="hljs-keyword">new</span> Student(<span class="hljs-number">21</span>, <span class="hljs-string">&quot;郑开&quot;</span>,<br>                <span class="hljs-string">&quot;杨晨学姐太强了&quot;</span>, <span class="hljs-string">&quot;拍了拍杨晨&quot;</span>);<br>        People robot = <span class="hljs-keyword">new</span> People(<span class="hljs-number">0</span>, <span class="hljs-string">&quot;1024&quot;</span>, <span class="hljs-string">&quot;你们肯定猜不到我是机器人&quot;</span>, <span class="hljs-string">&quot;喝了一口机油&quot;</span>) &#123;<br>            <span class="hljs-meta">@Override</span><br>            <span class="hljs-function"><span class="hljs-keyword">protected</span> String <span class="hljs-title">words</span><span class="hljs-params">()</span> </span>&#123;<br>                <span class="hljs-keyword">return</span> words;<br>            &#125;<br><br>            <span class="hljs-meta">@Override</span><br>            <span class="hljs-function"><span class="hljs-keyword">protected</span> String <span class="hljs-title">action</span><span class="hljs-params">()</span> </span>&#123;<br>                <span class="hljs-keyword">return</span> name + <span class="hljs-string">&quot;机器人&quot;</span> + action + <span class="hljs-string">&quot;。&quot;</span>;<br>            &#125;<br><br>            <span class="hljs-meta">@Override</span><br>            <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">answerQuestion</span><span class="hljs-params">(String answer)</span> </span>&#123;<br>                System.out.println(<span class="hljs-string">&quot;A--Robot &quot;</span> + name + <span class="hljs-string">&quot; :&quot;</span>);<br>                <span class="hljs-keyword">if</span> (answer == <span class="hljs-keyword">null</span>) &#123;<br>                    System.err.println(<span class="hljs-string">&quot;机器故障：NullPointerException&quot;</span>);<br>                    <span class="hljs-keyword">return</span>;<br>                &#125;<br>                System.out.println(<span class="hljs-string">&quot;答案是：&quot;</span> + answer);<br>            &#125;<br><br>            <span class="hljs-meta">@Override</span><br>            <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">askQuestion</span><span class="hljs-params">(Answerable answerable, String question)</span> </span>&#123;<br>                System.out.println(<span class="hljs-string">&quot;Q--Robot &quot;</span> + name + <span class="hljs-string">&quot; :&quot;</span>);<br>                question = <span class="hljs-string">&quot;你知道我的名字吗?&quot;</span>;<br>                System.out.println(<span class="hljs-string">&quot;问你个问题：&quot;</span> + question);<br>                answerable.answerQuestion(Classroom.getAnswer(question));<br>            &#125;<br>        &#125;;<br>        List&lt;People&gt; peoples = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();<br>        peoples.add(mbg);<br>        peoples.add(yc);<br>        peoples.add(zk);<br>        peoples.add(robot);<br>        <span class="hljs-keyword">for</span> (People people : peoples) &#123;<br>            people.doSomething();<br>        &#125;<br>        Classroom classroom = <span class="hljs-keyword">new</span> Classroom(<span class="hljs-string">&quot;twt&quot;</span>);<br>        classroom.addPeople(peoples);<br>        classroom.discuss();<br><br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>
</li>
<li><p>运行结果</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><code class="hljs java">=====================马保国的分割线=====================<br>马保国老师捂着红肿的眼睛。<br>然后说：<span class="hljs-string">&quot;年轻人不讲武德。今天我给大家讲一讲《武德》。&quot;</span><br>=====================马保国的分割线=====================<br>============================杨晨的分割线============================<br>杨晨老师露出开心的笑容。<br>然后说：<span class="hljs-string">&quot;我女妆真好看。今天我给大家讲一讲《女妆的一百零八种技巧》。&quot;</span><br>============================杨晨的分割线============================<br>==========郑开的分割线==========<br>郑开同学拍了拍杨晨。<br>然后说：<span class="hljs-string">&quot;杨晨学姐太强了。&quot;</span><br>==========郑开的分割线==========<br>==============<span class="hljs-number">1024</span>的分割线==============<br><span class="hljs-number">1024</span>机器人喝了一口机油。<br>然后说：<span class="hljs-string">&quot;你们肯定猜不到我是机器人。&quot;</span><br>==============<span class="hljs-number">1024</span>的分割线==============<br>Q--Student 郑开 :<br>我想问个问题：<span class="hljs-number">1</span>+<span class="hljs-number">1</span>=?<br>A--Teacher 杨晨 :<br>这道题的答案是：<span class="hljs-number">2</span><br>Q--Teacher 马保国 :<br>问题是：<span class="hljs-number">1</span>+<span class="hljs-number">1</span>=?<br>A--Teacher 杨晨 :<br>这道题的答案是：<span class="hljs-number">2</span><br>Q--Student 郑开 :<br>我想问个问题：杨晨学姐美不美?<br>A--Robot <span class="hljs-number">1024</span> :<br>答案是：美！<br>Q--Teacher 马保国 :<br>问题是：杨晨学姐美不美?<br>A--Robot <span class="hljs-number">1024</span> :<br>答案是：美！<br>Q--Teacher 马保国 :<br>问题是：<span class="hljs-number">1</span>+<span class="hljs-number">1</span>=?<br>A--Student 郑开 :<br>答案是...我也不知道<br><br>Process finished with exit code <span class="hljs-number">0</span><br><br></code></pre></td></tr></table></figure>




</li>
</ul>
<h1 id="参考内容"><a href="#参考内容" class="headerlink" title="参考内容"></a>参考内容</h1><p><a target="_blank" rel="noopener" href="https://www.jianshu.com/p/41a7a975502d">Java泛型</a></p>
<p><a target="_blank" rel="noopener" href="https://blog.csdn.net/weixin_42574142/article/details/87125363">JAVA常见容器</a></p>
<p><a target="_blank" rel="noopener" href="https://gitee.com/AlexAnde/rookie-training-2020">demo代码仓库网址</a></p>
      </section>
      <section class="extra">
        
          <ul class="copyright">
  
    <li><strong>本文作者：</strong>Alex</li>
    <li><strong>本文链接：</strong><a href="https://alexande.gitee.io/2020/11/07/Java-%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E5%85%A5%E9%97%A8/index.html" title="https:&#x2F;&#x2F;alexande.gitee.io&#x2F;2020&#x2F;11&#x2F;07&#x2F;Java-%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E5%85%A5%E9%97%A8&#x2F;index.html">https:&#x2F;&#x2F;alexande.gitee.io&#x2F;2020&#x2F;11&#x2F;07&#x2F;Java-%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E5%85%A5%E9%97%A8&#x2F;index.html</a></li>
    <li><strong>版权声明：</strong>本博客所有文章均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" title="BY-NC-SA" target="_blank" rel="noopener">BY-NC-SA</a> 许可协议，转载请注明出处！</li>
  
</ul>
        
        
          <section class="donate">
  <div id="qrcode-donate">
    <img   class="lazyload" data-original="https://pic.izhaoo.com/alipay.jpg" src="" >
  </div>
  <div class="icon">
    <a href="javascript:;" id="alipay"><i class="iconfont iconalipay"></i></a>
    <a href="javascript:;" id="wechat"><i class="iconfont iconwechat-fill"></i></a>
  </div>
</section>
        
        
  <ul class="tag-list" itemprop="keywords"><li class="tag-list-item"><a class="tag-list-link" href="/tags/Java/" rel="tag">Java</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1/" rel="tag">面向对象</a></li></ul> 

        
  <nav class="nav">
    <a href="/2021/01/20/SRCNN/"><i class="iconfont iconleft"></i>超分辨-SRCNN</a>
    <a href="/2020/09/26/javassist2/">字节码增强（二）<i class="iconfont iconright"></i></a>
  </nav>

      </section>
      
    </section>
  </div>
</article></div>
      <div class="col-xl-3">
        
          
  <aside class="toc-wrap">
    <h3 class="toc-title">文章目录：</h3>
    <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%8A%BD%E8%B1%A1%E7%B1%BB"><span class="toc-text">抽象类</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%A4%9A%E6%80%81"><span class="toc-text">多态</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%8E%A5%E5%8F%A3"><span class="toc-text">接口</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8C%BF%E5%90%8D%E5%86%85%E9%83%A8%E7%B1%BB%E4%B8%8ELambda%E8%A1%A8%E8%BE%BE%E5%BC%8F"><span class="toc-text">匿名内部类与Lambda表达式</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%B3%9B%E5%9E%8B"><span class="toc-text">泛型</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B3%9B%E5%9E%8B%E7%B1%BB"><span class="toc-text">泛型类</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B3%9B%E5%9E%8B%E6%8E%A5%E5%8F%A3"><span class="toc-text">泛型接口</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B3%9B%E5%9E%8B%E6%96%B9%E6%B3%95"><span class="toc-text">泛型方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%B8%B8%E7%94%A8%E7%9A%84%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84"><span class="toc-text">常用的数据结构</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%80%E4%B8%AA%E4%BE%8B%E5%AD%90"><span class="toc-text">一个例子</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%8F%82%E8%80%83%E5%86%85%E5%AE%B9"><span class="toc-text">参考内容</span></a>
  </aside>

        
      </div>
    </div>
  </div>
</main>
  

<footer class="footer">
  <div class="footer-social"><a 
        href="tencent://message/?Menu=yes&uin=272991962 "
        target="_blank"
        class="footer-social-item"
        onMouseOver="this.style.color= '#12B7F5'" 
        onMouseOut="this.style.color='#33333D'">
          <i class="iconfont  iconQQ "></i>
      </a><a 
        href="https://github.com/zheng-kai "
        target="_blank"
        class="footer-social-item"
        onMouseOver="this.style.color= '#9f7be1'" 
        onMouseOut="this.style.color='#33333D'">
          <i class="iconfont  icongithub-fill "></i>
      </a><a 
        href="https://gitee.com/AlexAnde "
        target="_blank"
        class="footer-social-item"
        onMouseOver="this.style.color= '#9f7be1'" 
        onMouseOut="this.style.color='#33333D'">
          <i class="iconfont  gitee-fill-round "></i>
      </a><a 
        href="mailto:272991962@qq.com "
        target="_blank"
        class="footer-social-item"
        onMouseOver="this.style.color=  '#12B7F5'" 
        onMouseOut="this.style.color='#33333D'">
          <i class="iconfont  iconmail "></i>
      </a></div>
  
    <div class="footer-copyright"><p>Powered by <a target="_blank" href="https://hexo.io">Hexo</a>  |  Theme - <a target="_blank" href="https://github.com/izhaoo/hexo-theme-zhaoo">zhaoo</a></p></div>
  
</footer>
  
      <div class="fab fab-plus">
    <i class="iconfont iconplus"></i>
  </div>
  
  
  <div class="fab fab-up">
    <i class="iconfont iconcaret-up"></i>
  </div>
  
  
    <div class="scrollbar j-scrollbar">
  <div class="scrollbar-current j-scrollbar-current"></div>
</div>
  
  
    
<script src="/js/color-mode.js"></script>

  
</body>

<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>



  
<script src="https://cdn.bootcdn.net/ajax/libs/jquery.lazyload/1.9.1/jquery.lazyload.min.js"></script>




  
<script src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.js"></script>






  
<script src="https://cdn.bootcdn.net/ajax/libs/jquery.qrcode/1.0/jquery.qrcode.min.js"></script>




<script src="/js/utils.js"></script>
<script src="/js/script.js"></script>





  <script>
    (function () {
      var bp = document.createElement('script');
      var curProtocol = window.location.protocol.split(':')[0];
      if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
      } else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
      }
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
    })();
  </script>













</html>